/*
 * 实现ueditor的功能
 * */
const path = require('path');
const fs = require('fs');
const express = require('express');
var moment = require('moment');
var snowflake = require('node-snowflake').Snowflake;

let router = express.Router();
let ueditorUtil = require('./ueditorUtil');
let config = null;
let configPath = './config.json';
router.use('/ue', ueditorUtil(path.join(__dirname, '..', '..', 'public'), ueditorFun));

function getConfig() {
  if (config === null) {
    //json格式的字符串中,是不能包含有注释的.将注释替换为''
    var str = fs.readFileSync(path.join(__dirname, configPath));
    str = str.toString().replace(/\/\*.*?\*\//g,'');
    config = JSON.parse(str);
  }
  return config;
}
function formatFilePath(str, filename) {
  return str.replace(/{time}/g, new Date().getTime())
    .replace(/{yyyy}/g, moment().year())
    .replace(/{yy}/g, moment().format('YY'))
    .replace(/{mm}/g, moment().month()+1)
    .replace(/{dd}/g, moment().date())
    .replace(/{hh}/g, moment().hour())
    .replace(/{ii}/g, moment().minute())
    .replace(/{ss}/g, moment().second())
    .replace(/{rand:\d*?}/g, snowflake.nextId())
    .replace(/{filename}/g, filename)
    .replace(/{suffix}/g, path.extname(filename));
}

function ueditorFun(req, res, next) {
  // ueditor 客户发起上传图片请求
  if (req.query.action === 'uploadimage') {
    var foo = req.ueditor;
    var date = new Date();
    var imgname = req.ueditor.filename;
    var img_url = getConfig()['imagePathFormat'];
    if(img_url){
      img_url = formatFilePath(img_url, imgname);
    }else{
      img_url = '/public/ueditor/images/'+snowflake.nextId() + path.extname(tmpdir);
    }
    res.ue_up(img_url); //你只要输入要保存的地址 。保存操作交给ueditor来做
  }
  //  客户端发起图片列表请求
  else if (req.query.action === 'listimage') {
    var dir_url = getConfig()['imageManagerListPath'];
    res.ue_list(dir_url);  // 客户端会列出 dir_url 目录下的所有图片
  }
  // 客户端发起其它请求
  else {
    res.json(getConfig());
  }
};

module.exports = router;